package com.xiaoqi.store.controller;

import com.xiaoqi.store.entity.CartEntity;
import com.xiaoqi.store.entity.CartVO;
import com.xiaoqi.store.entity.JsonResult;
import com.xiaoqi.store.service.CateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author Rookie Coder
 * @Description 购物车控制层
 * @Date
 **/
@RestController
@RequestMapping("/carts")
@Slf4j
public class CartController extends BaseController{

    @Autowired
    private CateService cateService;
    /*
    * @Author xiaoqi
    * @Description 添加商品到用户的购物车中
    * @return
    **/
    @PostMapping("/add_to_cart")
    public JsonResult<Void> addProductToCart(@Param("pid") Integer pid, @Param("amount") Integer amount, HttpSession session){
        Integer uidFromSession = getUidFromSession(session);
        String usernameFromSession = getUsernameFromSession(session);
        cateService.addProductToCart(pid,amount,uidFromSession,usernameFromSession);
        return new JsonResult<>(OK);
    }

    /*
    * @Author xiaoqi
    * @Description  用户购物车界面
    * @return
    **/
    @GetMapping({"", "/"})
    public JsonResult<List<CartVO>> getUserAllCarts(HttpSession session){
        Integer uidFromSession = getUidFromSession(session);
        String usernameFromSession = getUsernameFromSession(session);
        // List<CartVO> userCartFromSession = getUserCartFromSession(session);
        // 如果购物车为空，调用service层查出所有的购物车
        //if (userCartFromSession == null){
            log.info("session中的购物车为空");
           List<CartVO> userCartFromSession = cateService.selectUserAllCartsByUid(uidFromSession,usernameFromSession);
            // 将这个结果存入到session中
            log.info("查询出来的购物车 "+userCartFromSession);
        // session.setAttribute("AllUserCart",userCartFromSession);
        //}

        return new JsonResult<>(OK,userCartFromSession);
    }

    /*
    * @Author xiaoqi
    * @Description  修改购物车的数量
    * @return url: "/carts/" + cid + "/num/add",
    **/
    @PostMapping("{cid}/num/add")
    public JsonResult updateCartMount(@PathVariable("cid")Integer cid,HttpSession session){
        Integer uidFromSession = getUidFromSession(session);
        cateService.updateCartMount(cid,uidFromSession);
        return new JsonResult(OK);
    }

    /*
    * @Author xiaoqi
    * @Description  显示勾选的购物车数据
    * @return
    **/
    @GetMapping("/list")
    public JsonResult<List<CartVO>> getVOByCids(Integer[] cids, HttpSession session) {
        // 从Session中获取uid
        Integer uid = getUidFromSession(session);
        // 调用业务对象执行查询数据
        List<CartVO> data = cateService.getVOByCids(uid, cids);
        // 返回成功与数据
        return new JsonResult<>(OK, data);
    }


}
